'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { TextField, Button, Container, Box, Typography, Alert, CircularProgress } from '@mui/material';
import Link from 'next/link';

const LoginPage = () => {
  const router = useRouter();
  const [formData, setFormData] = useState({
    username: '',
    password: '',
  });
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [redirectUrl, setRedirectUrl] = useState('/');

  // 从URL获取redirectUrl参数
  React.useEffect(() => {
    if (typeof window !== 'undefined') {
      const url = new URL(window.location.href);
      const redirect = url.searchParams.get('redirect');
      if (redirect) {
        setRedirectUrl(redirect);
        console.log('检测到重定向URL:', redirect);
      }
    }
  }, []);

  // 检查用户是否已经登录
  React.useEffect(() => {
    const checkLoginStatus = async () => {
      try {
        // 检查localStorage中是否有token
        const token = localStorage.getItem('token');
        if (!token) {
          console.log('本地存储中没有token，用户未登录');
          return;
        }

        // 调用登录状态检查API
        const response = await fetch('/api/auth/check', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });

        const data = await response.json();

        if (response.ok && data.authenticated) {
          console.log('用户已登录，准备重定向');
          setIsLoggedIn(true);
          // 如果用户已登录，重定向到目标页面或首页
          if (redirectUrl && redirectUrl !== '/') {
            console.log(`重定向到指定页面: ${redirectUrl}`);
            router.push(redirectUrl);
          } else {
            console.log('重定向到首页');
          router.push('/');
          }
        } else {
          console.log('登录状态检查失败，清除本地存储');
          // 清除无效的token和用户数据
          localStorage.removeItem('token');
          localStorage.removeItem('user');
        }
      } catch (err) {
        console.error('检查登录状态时发生错误:', err);
      }
    };

    checkLoginStatus();
  }, [router]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    // 验证表单数据
    if (!formData.username.trim()) {
      setError('请输入用户名');
      setLoading(false);
      return;
    }

    if (!formData.password) {
      setError('请输入密码');
      setLoading(false);
      return;
    }

    try {
      console.log('提交登录表单:', { username: formData.username, passwordLength: formData.password.length });

      // 添加调试信息
      const debugElement = document.createElement('div');
      debugElement.id = 'login-debug-info';
      debugElement.style.position = 'fixed';
      debugElement.style.bottom = '10px';
      debugElement.style.left = '10px';
      debugElement.style.backgroundColor = 'rgba(0,0,0,0.7)';
      debugElement.style.color = 'white';
      debugElement.style.padding = '10px';
      debugElement.style.borderRadius = '5px';
      debugElement.style.zIndex = '9999';
      debugElement.style.maxWidth = '80%';
      debugElement.style.overflow = 'auto';
      debugElement.style.maxHeight = '200px';
      debugElement.innerHTML = '正在发送登录请求...';
      document.body.appendChild(debugElement);

      const updateDebug = (message: string) => {
        const el = document.getElementById('login-debug-info');
        if (el) {
          el.innerHTML += '<br>' + message;
          el.scrollTop = el.scrollHeight;
        }
      };

      // 使用绝对路径发送请求
      const apiUrl = window.location.origin + '/api/login';
      updateDebug(`发送请求到: ${apiUrl}`);

      const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
        credentials: 'same-origin', // 确保发送和接收cookie
      });

      updateDebug(`响应状态: ${response.status} ${response.statusText}`);

      // 获取响应数据
      let data;
      try {
        const textResponse = await response.text();
        updateDebug(`原始响应: ${textResponse.substring(0, 100)}${textResponse.length > 100 ? '...' : ''}`);

        // 尝试解析JSON
        data = JSON.parse(textResponse);
        console.log('服务器响应:', data);
        updateDebug(`解析的JSON数据: ${JSON.stringify(data).substring(0, 100)}...`);
      } catch (jsonError) {
        console.error('解析响应JSON失败:', jsonError);
        updateDebug(`解析JSON失败: ${jsonError instanceof Error ? jsonError.message : '未知错误'}`);
        throw new Error('服务器响应格式错误');
      }

      if (!response.ok) {
        updateDebug(`响应不成功: ${data.error || '未知错误'}`);
        throw new Error(data.error || '登录失败');
      }

      updateDebug('登录成功，准备存储数据');

      // 保存token和用户信息到localStorage
      try {
        updateDebug('清除旧数据...');
        // 清除旧数据
        localStorage.clear(); // 完全清除所有本地存储数据

        // 检查token是否存在
        if (!data.token) {
          updateDebug('错误: 响应中缺少token');
          throw new Error('服务器响应中缺少token');
        }

        // 检查用户数据是否存在
        if (!data.user) {
          updateDebug('错误: 响应中缺少用户数据');
          throw new Error('服务器响应中缺少用户数据');
        }

        updateDebug('存储新数据...');
        // 存储新数据
        try {
          localStorage.setItem('token', data.token);
          updateDebug(`token已存储 (长度: ${data.token.length})`);
        } catch (tokenError) {
          updateDebug(`存储token失败: ${tokenError instanceof Error ? tokenError.message : '未知错误'}`);
          throw tokenError;
        }

        // 确保用户数据是有效的JSON字符串
        try {
          const userDataString = JSON.stringify(data.user);
          localStorage.setItem('user', userDataString);
          updateDebug(`用户数据已存储 (长度: ${userDataString.length})`);
        } catch (userError) {
          updateDebug(`存储用户数据失败: ${userError instanceof Error ? userError.message : '未知错误'}`);
          throw userError;
        }

        console.log('登录成功，即将跳转到首页');
        console.log('存储的token:', data.token.substring(0, 20) + '...');
        console.log('存储的用户ID:', data.user.id);

        // 验证数据已正确存储
        const storedToken = localStorage.getItem('token');
        const storedUser = localStorage.getItem('user');
        updateDebug(`验证存储: token ${storedToken ? '存在' : '不存在'}, user ${storedUser ? '存在' : '不存在'}`);

        if (!storedToken || !storedUser) {
          updateDebug('错误: 数据存储后无法读取');
          throw new Error('数据存储失败');
        }

        // 触发存储事件，确保其他组件能感知到变化
        try {
          window.dispatchEvent(new Event('storage'));
          updateDebug('已触发storage事件');
        } catch (eventError) {
          updateDebug(`触发事件失败: ${eventError instanceof Error ? eventError.message : '未知错误'}`);
          // 不中断流程
        }

        // 显示成功消息
        setError('');
        updateDebug('登录成功，准备跳转...');

        // 获取重定向URL
        let redirectTo = '/';
        try {
          const urlObj = new URL(window.location.href);
          const redirectParam = urlObj.searchParams.get('redirect');
          if (redirectParam) {
            redirectTo = redirectParam;
            updateDebug(`检测到重定向参数: ${redirectTo}`);
          } else {
            updateDebug('没有重定向参数，将返回首页');
          }
        } catch (urlError) {
          updateDebug(`解析URL参数错误: ${urlError instanceof Error ? urlError.message : '未知错误'}`);
        }

        // 使用表单提交方式跳转，避免客户端路由问题
        const form = document.createElement('form');
        form.method = 'GET';
        form.action = redirectTo;
        document.body.appendChild(form);

        updateDebug(`即将跳转到: ${redirectTo}...`);
        setTimeout(() => {
          form.submit();
        }, 2000); // 增加延迟，确保用户可以看到调试信息
      } catch (storageError) {
        console.error('存储用户数据失败:', storageError);
        updateDebug(`存储错误: ${storageError instanceof Error ? storageError.message : '未知错误'}`);
        throw new Error('登录成功，但无法保存用户信息');
      }
    } catch (err) {
      console.error('登录过程中发生错误:', err);
      const errorMessage = (err as Error).message;
      setError(errorMessage);

      // 更新调试信息
      try {
        const debugEl = document.getElementById('login-debug-info');
        if (debugEl) {
          debugEl.innerHTML += `<br><span style="color: red; font-weight: bold">错误: ${errorMessage}</span>`;
          debugEl.scrollTop = debugEl.scrollHeight;
        }
      } catch (debugError) {
        console.error('更新调试信息失败:', debugError);
      }
    } finally {
      setLoading(false);

      // 3秒后移除调试信息
      setTimeout(() => {
        try {
          const debugEl = document.getElementById('login-debug-info');
          if (debugEl && debugEl.parentNode) {
            debugEl.parentNode.removeChild(debugEl);
          }
        } catch (cleanupError) {
          console.error('清理调试元素失败:', cleanupError);
        }
      }, 10000); // 10秒后移除调试信息
    }
  };

  return (
    <Container maxWidth="sm">
      <Box
        sx={{
          mt: 8,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          bgcolor: 'background.paper',
          p: 3,
          borderRadius: 2,
          boxShadow: 3
        }}
      >
        <Typography component="h1" variant="h5">
          登录
        </Typography>

        {error && (
          <Alert severity="error" sx={{ width: '100%', mt: 2 }}>
            {error}
          </Alert>
        )}

        <Box component="form" onSubmit={handleSubmit} sx={{ mt: 1, width: '100%' }}>
          <TextField
            margin="normal"
            required
            fullWidth
            id="username"
            label="用户名"
            name="username"
            autoComplete="username"
            autoFocus
            value={formData.username}
            onChange={handleChange}
          />
          <TextField
            margin="normal"
            required
            fullWidth
            name="password"
            label="密码"
            type="password"
            id="password"
            autoComplete="current-password"
            value={formData.password}
            onChange={handleChange}
          />
          <Button
            type="submit"
            fullWidth
            variant="contained"
            sx={{ mt: 3, mb: 2 }}
            disabled={loading}
          >
            {loading ? (
              <>
                <CircularProgress size={24} sx={{ mr: 1, color: 'white' }} />
                登录中...
              </>
            ) : '登录'}
          </Button>
          <Box sx={{ mt: 2, textAlign: 'center' }}>
            <Link href="/register" style={{ textDecoration: 'none' }}>
              <Typography variant="body2" color="primary">
                没有账号？立即注册
              </Typography>
            </Link>
          </Box>
        </Box>
      </Box>
    </Container>
  );
};

export default LoginPage;